define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'ocation/ocation/index',
                    add_url: 'ocation/ocation/add',
                    edit_url: 'ocation/ocation/edit',
                    multi_url: 'ocation/ocation/multi',
                    del_url: 'ocation/ocation/del',
                    export_url: 'coursetable/classplant/export',
                    table: 'fa_ocation',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                queryParams: function (params) {
                    params.rel_type = Config.relType;
                    params.rel_id = Config.relId;
                    return params;
                },
                rowAttributes: function (row, index) {
                    if (row.parent == '#') {
                        return {class: 'disabled-row'}; // 添加禁用样式
                    }
                    return {};
                },
                escape: false,
                pageSize: 5000,
                pk: 'id',
                sortName: 'id', //要使排序生效，在前面添加 weigh desc, 并且数据表weigh字段不能全为0,controller里$list=...->order前再添加->order("weigh desc")
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'parent', title: "父ID"},
                        {field: 'name', title: '教学点名称',align: 'left'},
                        {field: 'entvirt', title: '实体或虚拟',align: 'left'},
                        {field: 'address_lv_octionlevel', title: '教学点级别',align: 'left'},
                        {field: 'ocation_type', title: '教室类型',align: 'left'},
                        {field: 'weekdays', title: '周几',align: 'left'},
                        {field: 'address', title: '地址',align: 'left'},
                        {field: 'endtime', title: '使用截止时间',align: 'left'},
                        {field: 'status', title: '状态', operate: false, formatter:Controller.api.formatter.changeStatus},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                // {
                                //     name: 'detail',
                                //     classname: 'btn btn-xs btn-primary btn-click',
                                //     icon: 'fa fa-sitemap',
                                //     click: function (value, row, index) {
                                //         Backend.api.open('/adminht.php/dept/dept?relType=school&relId='+row.id+'&ref=addtabs', '组织结构2', {
                                //             max: true,
                                //             area: ['80%', '80%'],
                                //             //offset: ['0px', '0px'],
                                //             callback: function (data) {
                                //                 Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                //             }
                                //         });
                                //     }
                                // }
                            ]
                        }
                    ]
                ]
            });

            function toggleChildren(id, isChecked,index) {
                if(index>2) return;
                $('tbody tr').each(function() {
                    var pid = $(this).find('td:eq(2)').text(); // 获取当前行的PID
                    if (pid == id) {
                        var childId = $(this).find('td:eq(1)').text(); // 获取当前行的ID
                        $(this).find('input[name="btSelectItem"]').prop('checked',isChecked);
                        toggleChildren(childId, isChecked,2); // 递归处理子节点
                    }
                });
            }

            table.on('load-success.bs.table', function (e, data) {
                $(".lv1,.lv2").css("cursor","pointer");
                $("#table").on("click mouseup","input[name=btSelectItem],.lv1,.lv2",function() {
                    var selectedId = $(this).closest('tr').find('td:eq(1)').text(); // 获取当前行的ID
                    var isChecked = $(this).closest('tr').find('input[name=btSelectItem]').prop('checked'); // 获取当前复选框的状态
                    toggleChildren(selectedId, isChecked,1); // 递归处理子节点
                });
            });

            table.on('load-success.bs.table', function (e, data) {
                // 绑定导出按钮点击事件
                $(document).on("click",".btn-export", function () {
                    var selectedRows = table.bootstrapTable('getSelections');
                    var ids = [];
                    for (var i = 0; i < selectedRows.length; i++) {
                        ids.push(selectedRows[i].id); // 假设数据中的 id 字段存储的是唯一标识
                    }
                    var exportUrl = $.fn.bootstrapTable.defaults.extend.export_url;
                    if (ids.length > 0) {
                        var idParams = ids.join(',');
                        if (exportUrl.indexOf('?') === -1) {
                            exportUrl += '?ids=' + idParams;
                        } else {
                            exportUrl += '&ids=' + idParams;
                        }
                    }
                    var downloadIframe = $('#download-iframe');
                    if (downloadIframe.length === 0) {
                        downloadIframe = $('<iframe id="download-iframe" style="display: none;"></iframe>');
                        $('body').append(downloadIframe);
                    }
                    downloadIframe.attr('src', "/"+exportUrl);
                });
                if($("#message").length > 0){
                    $("#message").html(data.message);
                }
            });

            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            var script2 = document.createElement('script');
            script2.src = '/assets/js/backend/common/ocation.js';
            document.head.appendChild(script2);
            Controller.api.bindevent();
        },
        edit: function () {
            var row = JSON.parse($('#row').val());
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            var script2 = document.createElement('script');
            script2.src = '/assets/js/backend/common/ocation.js';
            document.head.appendChild(script2);
            Controller.api.bindevent();

        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                status: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="ocation/ocation/status" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status == 0 ||row.status == null ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                changeStatus: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success" data-url="ocation/ocation/changeStatus" data-confirm="确认切换状态？" data-id="' + row.id + '"><i class="fa ' + (row.status === 0 ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
            }
        }
    };
    return Controller;
});